<template>
  <div class="course-video">
    <el-card>
      <div slot="header">课程相关信息</div>
      <el-form ref="lessonInfo" :model="lessonInfo"
        label-width="180px"
        label-position="right">
        <el-form-item label="课程">
          <el-input type="text" v-model="lessonInfo.courseName" disabled></el-input>
        </el-form-item>
        <el-form-item label="课时">
          <el-input type="text" v-model="lessonInfo.lessonName" disabled></el-input>
        </el-form-item>
        <el-form-item label="视频上传">
          <input type="file" ref="video-file">
          <el-button type="primary">视频上传</el-button>
          <div>{{ lessonInfo.videoFile }}</div>
        </el-form-item>
        <el-form-item>
        </el-form-item>
        <el-form-item label="封面上传">
          <input type="file" ref="image-file">
          <el-button type="primary">封面上传</el-button>
        </el-form-item>
        <el-form-item>
          <img
            v-if="lessonInfo.imageFile"
            :src="lessonInfo.imageFile" style="width: 200px">
          <div v-else></div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleUploader">开始上传</el-button>
          <el-button @click="$router.push({
            name: 'course-section',
            params: {
              courseId
            }
          })">返回</el-button>
        </el-form-item>
        <el-form-item>
          <p v-if="uploadPercent !== 0">视频上传中{{ uploadPercent }}%</p>
          <p v-if="isUploadSuccess">{{ isTransCodeSuccess ? '视频转码完成' : '正在转码中...'}}</p>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getById } from '@/services/course-section'
import { getCourseById } from '@/services/course'
/* eslint-disable */
import { aliyunImagUploadAddressAndAuth, aliyunVideoUploadAddressAndAuth, aliyunVideoTransCode, aliyunTransCodePercent, getMediaByLessonId } from '@/services/aliyun-upload'

export default {
  name: 'CourseVideo',
  props: {
    courseId: {
      type: [String, Number],
      required: true
    },
    lessonId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      courseInfo: [],
      // 图片上传后的地址，用于视频上传请求
      imageURL: '',
      // 保存上传实例
      uploader: '',
      // 保存上传视频的 ID
      videoId: null,
      // 上传百分比
      uploadPercent: 0,
      // 上传完毕状态
      isUploadSuccess: false,
      // 转码完毕状态
      isTransCodeSuccess: false,
      lessonInfo: {
        courseName: '',
        lessonName: '',
        videoFile: '',
        imageFile: null

      }
    }
  },
  created () {
    // 加载已有信息
    this.loadCourseInfo()
    // 初始化上传工具
    this.initUploader()
  },
  methods: {
    /* eslint-disable */
    initUploader () {
      this.uploader = new window.AliyunUpload.Vod({
        //  userID，必填，只需有值即可。
        userId: '1618139964448548',
        //  上传到视频点播的地域，默认值为'cn-shanghai'，
        //  eu-central-1，ap-southeast-1
        region: '',
        //  分片大小默认1 MB，不能小于100 KB，此参数单位默认为 B
        partSize: 1048576,
        //  并行上传分片个数，默认5
        parallel: 5,
        //  网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        //  网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        //  开始上传
        onUploadstarted: async uploadInfo => {
          let uploadAddressAndAuth = null
          if (uploadInfo.isImage) {
            // 图片处理
            const { data } = await aliyunImagUploadAddressAndAuth()
            if (data.code === '000000') {
              uploadAddressAndAuth = data.data
              this.imageURL = uploadAddressAndAuth.imageURL
            }
          } else {
            // 视频处理
            const { data } = await aliyunVideoUploadAddressAndAuth({
              fileName: uploadInfo.file.name,
              imageUrl: this.imageURL
            })
            if (data.code === '000000') {
              uploadAddressAndAuth = data.data
              this.videoId = data.data.videoId
            }
          }
          // 设置凭证与地址
          this.uploader.setUploadAuthAndAddress(
            uploadInfo,
            uploadAddressAndAuth.uploadAuth,
            uploadAddressAndAuth.uploadAddress,
            uploadAddressAndAuth.imageId || uploadAddressAndAuth.videoId
          )
          // 此部设置完毕，上传进度开始执行
        },
        //  文件上传成功
        onUploadSucceed: function (uploadInfo) {
        },
        //  文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {
        },
        //  文件上传进度，单位：字节
        onUploadProgress: (uploadInfo, totalSize, loadedPercent) => {
          if (!uploadInfo.isImage) {
            this.uploadPercent = Math.floor(loadedPercent * 100)
          }
        },
        //  上传凭证或STS token超时
        onUploadTokenExpired: function (uploadInfo) {
        },
        //  全部文件上传结束
        onUploadEnd: async uploadInfo => {
          this.isUploadSuccess = true
          // 发送视频转码请求
          const { data } = await aliyunVideoTransCode({
            lessonId: this.lessonId,
            coverImageUrl: this.imageURL,
            fileId: this.videoId,
            fileName: this.$refs['video-file'].files[0].name
          })
          if (data.code === '000000') {
            // 轮询转码进度(即时不时去查一下)
            const timer = setInterval(async () => {
              const { data } = await aliyunTransCodePercent(this.lessonId)
              if (data.code === '000000') {
                this.transCodePercent = data.data
                if (data.data === 100) {
                  this.isTransCodeSuccess = true
                  this.$message.success('视频转码成功')
                  clearInterval(timer)
                }
              }
            }, 1000)
          }
        }
      })
    },
    // 点击上传按钮
    handleUploader () {
      // 考虑到可能重复使用某个组件进行上传处理，点击上传时，将数据重置
      this.uploadPercent = 0
      this.isUploadSuccess = false
      this.isTransCodeSuccess = false
      const videoFile = this.$refs['video-file'].files[0]
      const imageFile = this.$refs['image-file'].files[0]
      const uploader = this.uploader
      // 将要上传的文件添加到上传列表中
      uploader.addFile(imageFile)
      uploader.addFile(videoFile)
      // 开始上传
      uploader.startUpload()
    },
    async loadCourseInfo () {
      const { data } = await getCourseById(this.courseId)
      if (data.code === '000000') {
        this.lessonInfo.courseName = data.data.courseName
      }
      const { data: data2 } = await getById(this.lessonId)
      if (data2.code === '000000') {
        this.lessonInfo.lessonName = data2.data.theme || ''
      }
      const { data: data3 } = await getMediaByLessonId(this.lessonId)
      if (data3.code === '000000' && data3.data) {
        this.lessonInfo.videoFile = data3.data.fileName
        this.lessonInfo.imageFile = data3.data.coverImageUrl
      }
      
      
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-form {
    width: 800px;
    margin: 0 auto;
    .el-form-item {
      input {
        position: absolute;
        display: block;
        opacity: 0;
        width: 98px;
        height: 40px;
      }
    }
  }
</style>
